
const wxClassPath = "org/cocos2dx/javascript/WeChatModule";

const KeyRefreshToken = 'plaza_refresh_token';

const WxAccessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
const WxRefreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
 
const http = require('./HttpModule');

var WeChatModule = cc.Class({
    name: "WeChatModlue",

    properties: {
        appId: '',
        appSecret: '',
    },

    //构造函数
    ctor: function () {
        console.log(`[WeChatModule][ctor]---构造函数`);
        this.initWx(this.appId, this.appSecret);
    },

    //判断是否安装微信
    isInstallWx: function() {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            return jsb.reflection.callStaticMethod(
                wxClassPath, 
                "isInstallWx", 
                "()Z");
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            return jsb.reflection.callStaticMethod("WeChatModule", "isInstallWx");
        }
        return true;
    },

    //初始化接口 需要传入appId和secret
    initWx: function (appId, appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            return jsb.reflection.callStaticMethod(
                wxClassPath, 
                "initWx", 
                "(Ljava/lang/String;Ljava/lang/String;)V", appId, appSecret);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            return jsb.reflection.callStaticMethod("WeChatModule", "initWx:andSecret:", appId, appSecret);
        }
        return true;
    },

    loginWx: function () {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath, 
                "loginWx", 
                "()V");
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "loginWx");
        }
    },

    //微信支付
    payWx: function (content) {
        cc.log('[WeChatModule][payWx]--content: ' + content);
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath, 
                "payWx", 
                "(Ljava/lang/String;)V", 
                "" + content);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "payWx:", "" + content);
        } else {
            this.onWxPayResultCallback(false, 'win版本不支持支付');
        }
    },
    
    //type0好友 1朋友圈
    shareImageWx: function (imgPath, type) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath, 
                "shareImageWx", 
                "(Ljava/lang/String;I)V", imgPath, type);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "shareImageWx:andType:", imgPath, type);
        } else {
            this.onWxShareResultCallback(true);
        }
    },

    shareTextWx: function (text, type) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath, 
                "shareTextWx", 
                "(Ljava/lang/String;I)V", text, type);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "shareTextWx:andType:", text, type);
        } else {
            this.onWxShareResultCallback(true);
        }
    },

    shareUrlWx: function (url, title, desc, type) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath, 
                "shareUrlWx", 
                "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V", url, title, desc, type);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "shareUrlWx:andTitle:andDesc:andType:", url, title, desc, type);
        } else {
            this.onWxShareResultCallback(true);
        }
    },

    //微信登录
    login: function () {
        let strToken = cc.sys.localStorage.getItem(KeyRefreshToken);
        var self = this;
        if (strToken)
        {
            let token = JSON.parse(strToken);
            let appid = token.appid;
            let refresh_token = token.refresh_token;
            let kUrl = `${WxRefreshUrl}?appid=${appid}&grant_type=refresh_token&refresh_token=${refresh_token}`;
            http.get({url:kUrl,timeout:10000},function(err,result) {
                if (err || result.errcode){
                    self.resetWx();
                    self.loginWx();
                    return;
                } 
                let msg = {};
                msg.ret = true;
                msg.access_token = result.access_token;
                msg.openid = result.openid;
                let token = {};
                token.refresh_token = result.refresh_token;
                token.appid = appid;
                cc.sys.localStorage.setItem(KeyRefreshToken, JSON.stringify(token));
                cc.director.emit("WxLoginCallback", msg);
            }.bind(self));
            return true;
        }

        //检查是否安装微信
        if (this.isInstallWx() === false) {
            gg.fun.showAlert('微信登录失败，请检查是否安装微信');
            return false;
        }

        if (cc.sys.platform === cc.sys.WIN32) {
            gg.fun.createDialog('WechatLoginView', '', false);
            return true;
        } else {
            return this.loginWx();
        }
    },

    // 跳转小程序
    linkApplet: function(path, type) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            jsb.reflection.callStaticMethod(
                wxClassPath,
                "linkApplet",                
                "(Ljava/lang/String;I)V", path, type);
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod("WeChatModule", "linkApplet:andType:", path, type);
        } else {
            this.onlinkAppletCallback(true);
        }
    },   

    onWxLoginResultCallback: function (result, codeMsg) {
        if (result === false) {
            let msg = {};
            msg.ret = false;
            msg.msg = '微信登录失败，' + codeMsg;
            cc.director.emit("WxLoginCallback", msg);
            return;   
        }

        var self = this;
        let kUrl = `${WxAccessUrl}?appid=${this.appId}&secret=${this.appSecret}&code=${codeMsg}&grant_type=authorization_code`;
        http.get({url:kUrl,timeout:10000},function(err,result) {
            if (err || result.errcode) {
                self.resetWx();
                let msg = {};
                msg.ret = false;
                msg.msg = '微信登录失败,请稍后重试';
                cc.director.emit("WxLoginCallback", msg);
                return;
            } 
            let msg = {};
            msg.ret = true;
            msg.access_token = result.access_token;
            msg.openid = result.openid;
            let token = {};
            token.refresh_token = result.refresh_token;
            token.appid = self.appid;
            cc.sys.localStorage.setItem(KeyRefreshToken, JSON.stringify(token));
            cc.director.emit("WxLoginCallback", msg);
        });
    },

    onWxShareResultCallback: function (result, msg) {

    },

    onWxPayResultCallback: function (result, msg) {

    },

    onWindowLoginCallback: function (appId, appSecret, code) {
        this.appId = appId;
        this.appSecret = appSecret;
        this.onWxLoginResultCallback(true, code);
    },
    
    onlinkAppletCallback: function(result, msg) {
            
    },

    resetWx: function () {
        cc.sys.localStorage.removeItem(KeyRefreshToken);
    },
});

module.exports = WeChatModule;